package live.ifox.stage;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import live.ifox.base.BaseRestActivity;
import live.ifox.factory.Entry;
import live.ifox.factory.ID;
import live.ifox.factory.Url;
import live.ifox.helper.AdapterHelper;
import live.ifox.helper.CommonHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DialActivity extends BaseRestActivity {
    ListView listView;
    SwipeRefreshLayout swipeLayout;
    JSONArray array;
    boolean callFlag;
    String _phone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dial);
        actionBar.setDisplayHomeAsUpEnabled(false);
        actionBar.setTitle("业务计划");

        entry = Entry.MedicalDial;
        baseUrl = Url.MedicalDial;
        listView = findViewById(R.id.listView);
        registerForContextMenu(listView);
        callFlag = checkPermission(Manifest.permission.CALL_PHONE);

        swipeLayout = findViewById(R.id.swipeLayout);
        swipeLayout.setOnRefreshListener(() -> {
            swipeLayout.setRefreshing(false);
            updateView();
        });
        updateView();
    }

    void updateView() {
        httpGet(baseUrl + "get_detail");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, ID.ACTION_ADD, 0, "添加...");
        menu.add(0, ID.ACTION_CHOICE, 1, "选择...");
        menu.add(0, ID.CONTACT, 2, "通信录");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case ID.ACTION_ADD:
                startActivity(new Intent(this,
                        DialEditor.class));
                return true;
            case ID.ACTION_CHOICE:
                startActivityForResult(new Intent(this,
                                ContactActivity.class)
                                .putExtra("choice", 1),
                        ID.ACTION_CHOICE);
                return true;
            case ID.CONTACT:
                startActivity(new Intent(this,
                        ContactActivity.class));
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, ID.ACTION_SMS, 0, "发短信");
        menu.add(0, ID.ACTION_DIAL, 1, "拨号");
        menu.add(0, ID.ACTION_EDIT, 2, "编辑...");
        menu.add(0, ID.ACTION_CALL, 3, "直接拨打");
        menu.add(0, ID.ACTION_DO_FINISHED, 4, "已完成");
        menu.add(0, ID.ACTION_REMOVE, 5, "删除");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (array == null || array.isEmpty())
            return false;

        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        int position = info.position;
        JSONObject object = array.getJSONObject(position);
        if (object == null || object.isEmpty())
            return false;

        switch (item.getItemId()) {
            case ID.ACTION_EDIT:
                return do_editItem(object);
            case ID.ACTION_SMS:
                return do_sendSMS(object);
            case ID.ACTION_DIAL:
                return do_dialItem(object);
            case ID.ACTION_CALL:
                do_callItem(object);
                return true;
            case ID.ACTION_DO_FINISHED:
                return do_finished(object);
            case ID.ACTION_REMOVE:
                return do_removeItem(object);
        }
        return super.onContextItemSelected(item);
    }

    boolean do_editItem(JSONObject object) {
        int id = object.getIntValue("id");
        String name = object.getString("name");
        String phone = object.getString("phone");
        String remark = object.getString("remark");
        if (id == 0 || name.isEmpty() || phone.isEmpty())
            return false;

        Intent intent = new Intent(this,
                DialEditor.class);
        intent.putExtra("id", id);
        intent.putExtra("name", name);
        intent.putExtra("phone", phone);
        intent.putExtra("remark", remark);
        startActivityForResult(intent, ID.DIAL_EDITOR);
        return true;
    }

    boolean do_dialItem(JSONObject object) {
        _phone = object.getString("phone");
        if (_phone == null || _phone.isEmpty())
            return false;

        Intent intent = new Intent(Intent.ACTION_DIAL,
                Uri.parse("tel:" + _phone));
        startActivity(intent);
        return true;
    }

    boolean do_sendSMS(JSONObject object) {
        _phone = object.getString("phone");
        if (_phone == null || _phone.isEmpty())
            return false;

        Intent intent = new Intent(Intent.ACTION_SENDTO,
                Uri.parse("smsto:" + _phone));
        startActivity(intent);
        return true;
    }

    void do_callItem(JSONObject object) {
        _phone = object.getString("phone");
        if (_phone == null || _phone.isEmpty())
            return;

        if (callFlag) {
            Intent intent = new Intent(Intent.ACTION_CALL,
                    Uri.parse("tel:" + _phone));
            startActivity(intent);
        } else
            requestPermission(new String[]{Manifest.permission.CALL_PHONE},
                    ID.ACTION_CALL);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions,
                                           int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == ID.ACTION_CALL) {
            int grantResult = grantResults[0];
            if (grantResult != PackageManager.PERMISSION_GRANTED) {
                callFlag = false;
                CommonHelper.showMessage(this, "缺少权限，无法拨打！");
            } else {
                callFlag = true;
                Intent intent = new Intent(Intent.ACTION_CALL,
                        Uri.parse("tel:" + _phone));
                startActivity(intent);
            }
        }
    }

    boolean do_finished(JSONObject object) {
        return do_updateItem(object, "addition", "finished");
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == ID.RESULT_DONE) {
            updateView();
        }
    }

    @Override
    public void processReply(JSONObject rootObject) {
        if (rootObject.containsKey("detail")) {
            array = rootObject.getJSONArray("detail");
            if (array.isEmpty()) {
                listView.setAdapter(null);
                return;
            }

            List<Map<String, Object>> model = new ArrayList<>();
            for (int i = 0; i < array.size(); i++) {
                JSONObject object = array.getJSONObject(i);
                Map<String, Object> item = new HashMap<>();
                item.put("date_", object.getString("date_"));
                String detail = object.getString("name") + "  " +
                        object.getString("phone") + "  " +
                        object.getString("remark");
                item.put("detail", detail);
                model.add(item);
            }
            if (!model.isEmpty()) {
                SimpleAdapter adapter = AdapterHelper.getTableAdapter(this,
                        model, new String[]{"date_", "detail"});
                listView.setAdapter(adapter);
            }
        } else if (rootObject.containsKey("removed")) {
            updateView();
        }
    }
}
